package controllers;

import java.io.IOException;
import java.util.Calendar;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.DealModel;
import models.OrderModel;
import models.UserModel;
import admin.data.DealData;
import data.GeoData;
import data.OrderData;
import data.UserData;

@SuppressWarnings("serial")
public class CheckOutServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(CheckOutServlet.class
			.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		String[] splitted = request.getRequestURI().split("/");
		if (splitted.length == 2) {
			int validStep1 = 3;
			int validStep2 = 3;
			int validStep3 = 3;
			String act = request.getParameter("act");
			HttpSession session = request.getSession();
			OrderModel order = (OrderModel) session.getAttribute("user_order");
			if (order != null) {
				UserModel user = (UserModel) session
						.getAttribute("user_logged_in");
				if (act != null && act.equals("doi-thong-tin")) {
					validStep1 = 2;
				} else if (act != null && act.equals("doi-tai-khoan")) {
					validStep1 = 3;
					user = null;
				} else if (act != null && act.equals("doi-thong-tin-order")) {
					if (user != null) {
						validStep1 = 1;
					}
					validStep2 = 3;
				} else if (act != null
						&& act.equals("doi-thong-tin-thanh-toan")) {
					if (user != null) {
						validStep1 = 1;
						if (user.isFullProfile()) {
							order = transferInfor(user, order);
							validStep2 = 1;
						}
					}
					validStep3 = 3;
				} else {
					if (user != null) {
						validStep1 = 1;
						if (user.isFullProfile()) {
							DealModel deal = DealData
									.getById(order.getDealId());
							if (user.getCity() != null
									&& !user.getCity().equals(deal.getCity())) {
								validStep2 = 3;
							} else {
								validStep2 = 1;
								order = transferInfor(user, order);
								if (order.getPaymentType() == 1) {
									validStep3 = 1;
								}
							}
						}
					}
				}
				session.setAttribute("user_order", order);
				session.setAttribute("user_logged_in", user);
				request.setAttribute("validStep1", validStep1);
				request.setAttribute("validStep2", validStep2);
				request.setAttribute("validStep3", validStep3);
				request.getRequestDispatcher("/pages/check_out.jsp").forward(
						request, response);

			} else {
				response.sendRedirect("/don-hang");
			}
		} else {
			System.out
					.println("Error when try to view check out form with invalid url !");
			log.warning("Error when try to view check out form with invalid url !");
			request.getRequestDispatcher("/pages/error.jsp").forward(request,
					response);
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			int validStep1 = 3;
			int validStep2 = 3;
			int validStep3 = 3;
			HttpSession session = req.getSession();
			String action = req.getParameter("action");
			UserModel user = (UserModel) session.getAttribute("user_logged_in");
			OrderModel order = (OrderModel) session.getAttribute("user_order");
			if (order != null) {
				if (action != null && action.equals("login")) {
					String username = req.getParameter("username");
					String password = req.getParameter("password");
					TreeMap check = new TreeMap();
					if (username == null || username.isEmpty()) {
						check.put("username", "Bạn cần nhập địa chỉ email.");
					}
					if (password == null || password.isEmpty()) {
						check.put("password", "Bạn cần nhập mật khẩu.");
					}
					if (check.size() != 0) {
						req.setAttribute("check", check);
					} else {
						UserData userData = new UserData();
						user = userData.getUserLogin(username, password);
						if (user != null && !user.getUsername().equals("")) {
							validStep1 = 1;
							if (user.isFullProfile()) {

								DealModel deal = DealData.getById(order
										.getDealId());
								if (user.getCity() != null
										&& !user.getCity().equals(
												deal.getCity())) {
									validStep2 = 3;
								} else {
									order = transferInfor(user, order);
									validStep2 = 1;
								}
							}
						} else {
							check.put("username",
									"Thông tin tài khoản không chính xác.");
							req.setAttribute("check", check);
						}
					}
				} else if (action != null && action.equals("changeInfor")) {
					if (user != null) {
						validStep1 = 2;
						UserData userData = new UserData();
						String username = req.getParameter("username");
						String gender = req.getParameter("gender");
						TreeMap check = new TreeMap();

						if (username != null
								&& username.equals(user.getUsername())) {
							validStep1 = 1;
							if (user.isFullProfile()) {								
								DealModel deal = DealData.getById(order
										.getDealId());
								if (user.getCity() != null
										&& !user.getCity().isEmpty()
										&& !user.getCity().equals(
												deal.getCity())) {
									validStep2 = 3;
								} else {
									order = transferInfor(user, order);
									validStep2 = 1;
								}
							}
						} else {
							if (username == null || username.isEmpty()) {
								check.put("username",
										"Bạn cần nhập địa chỉ email.");
							}
							if (userData.getUser(username) != null) {
								check.put("username",
										"Email đã được sử dụng. Xin chọn email khác !");
							}
							if (check.size() != 0) {
								req.setAttribute("check", check);
							} else {
								userData.delete(user);
								user.setUsername(username);
								if (gender.equals("0")) {
									user.setGender(0);
								} else {
									user.setGender(1);
								}
								userData.insert(user);
								validStep1 = 1;
								if (user.isFullProfile()) {									
									DealModel deal = DealData.getById(order
											.getDealId());
									if (user.getCity() != null
											&& !user.getCity().isEmpty()
											&& !user.getCity().equals(
													deal.getCity())) {
										validStep2 = 3;
									} else {
										order = transferInfor(user, order);
										validStep2 = 1;
									}
								}
							}
						}
					} else {
						validStep1 = 3;
					}
				} else if (action != null && action.equals("setOrder")) {
					if (user != null && !user.getUsername().equals("")) {
						validStep1 = 1;

						String shipName = req.getParameter("shipName");
						String city = req.getParameter("city");
						String district = req.getParameter("district");
						String ward = req.getParameter("ward");
						String address = req.getParameter("address");
						String street = req.getParameter("street");
						String floor = req.getParameter("floor");
						String phone = req.getParameter("phone");

						TreeMap check = new TreeMap();

						if (shipName == null || shipName.isEmpty()) {
							check.put("shipName",
									"Bạn cần nhập tên người nhận.");
						}
						if (city == null || city.isEmpty()) {
							check.put("city", "Bạn cần chọn tỉnh/thành phố.");
						}						
						DealModel deal = DealData.getById(order.getDealId());
						if (city != null && !city.equals(deal.getCity())) {
							check.put("city",
									"Deal hiện tại không được cung cấp tại tỉnh thành này.");
						}
						if (district == null || district.isEmpty()) {
							check.put("district", "Bạn cần chọn quận/huyện.");
						}
						if (ward == null || ward.isEmpty()) {
							check.put("ward", "Bạn cần chọn phường/xã.");
						}
						if (address == null || address.isEmpty()) {
							check.put("address", "Bạn cần nhập địa chỉ.");
						}
						if (street == null || street.isEmpty()) {
							check.put("street", "Bạn cần nhập tên đường.");
						}
						if (phone == null || phone.isEmpty()) {
							check.put("phone", "Bạn cần nhập số điện thoại.");
						}
						if (check.size() != 0) {
							req.setAttribute("check", check);
						} else {
							if (order != null) {
								order.setShipName(shipName);
								order.setShipCity(city);
								order.setShipDistrict(district);
								order.setShipWard(ward);
								order.setShipAddress(address);
								order.setShipStreet(street);
								order.setShipFloor(floor);
								order.setShipPhoneNumber(phone);								
								validStep2 = 1;
							}
						}
					}
				} else if (action != null && action.equals("paymentType")) {
					if (user != null && !user.getUsername().equals("")) {
						validStep1 = 1;
						if (user.isFullProfile()) {
							order = transferInfor(user, order);
							validStep2 = 1;
							String paymentType = req.getParameter("payment");
							if (paymentType.equals("on")) {
								order.setPaymentType(1);
								validStep3 = 1;
							} else {
								order.setPaymentType(0);
								validStep3 = 1;
							}
						}
					}
				} else if (action != null && action.equals("finish")) {
					if (user != null && !user.getUsername().equals("")) {
						validStep1 = 1;
						if (user.isFullProfile()) {
							order = transferInfor(user, order);
							validStep2 = 1;
							if (order.getPaymentType() == 0) {
								validStep3 = 3;
							} else {
								String note = req.getParameter("note");
								if (note != null && !note.isEmpty()) {
									order.setNote(note);
								}
								
								DealModel deal = DealData.getById(order
										.getDealId());
								deal.setAmount(deal.getAmount() + 1);
								DealData.insert(deal);
								order.setOrderDate(Calendar.getInstance()
										.getTime());
								order.setUsername(user.getUsername());
								order.setDealName(deal.getName());
								order.setDealShortName(deal.getShortName());
								order.setDealProductType(deal.getProductType());
								GeoData geoData = new GeoData();
								StringBuilder temStr = new StringBuilder();
								if (order.getShipFloor() != null
										&& !order.getShipFloor().isEmpty()) {
									temStr.append("Tầng "
											+ order.getShipFloor() + ", ");
								}
								temStr.append(order.getShipAddress() + ", ");
								temStr.append(order.getShipStreet() + ", ");
								temStr.append(geoData.getGeo(
										order.getShipWard()).getName()
										+ ", ");
								temStr.append(geoData.getGeo(
										order.getShipDistrict()).getName()
										+ ", ");
								temStr.append(geoData.getGeo(
										order.getShipCity()).getName());

								order.setShipAddressFull(temStr.toString());
								order.setStatus(1);
								if (session.getAttribute("email_redirect") != null) {
									try {
										boolean booSession = (Boolean) session
												.getAttribute("email_redirect");
										if (booSession) {
											order.setFromEmail(1);
										} else {
											order.setFromEmail(0);
										}
									} catch (Exception e) {
										order.setFromEmail(0);
									}
								}
								OrderData orderData = new OrderData();
								orderData.insert(order);
								session.setAttribute("user_order", null);
								req.setAttribute("orderId", order.getOrderId());
								req.setAttribute("user", user);
								req.getRequestDispatcher(
										"/pages/order_success.jsp").forward(
										req, resp);
								return;
							}
						}
					}
				} else {
					req.getRequestDispatcher("/pages/error.jsp").forward(req,
							resp);
					return;
				}
				session.setAttribute("user_order", order);
				session.setAttribute("user_logged_in", user);
				req.setAttribute("validStep1", validStep1);
				req.setAttribute("validStep2", validStep2);
				req.setAttribute("validStep3", validStep3);
				req.getRequestDispatcher("/pages/check_out.jsp").forward(req,
						resp);
			} else {
				resp.sendRedirect("/don-hang");
			}
		} catch (Exception e) {
			System.out
					.println("Error when try to view check out form with invalid url !");
			log.warning("Error when try to view check out form with invalid url !");
			log.warning(e.toString());
			e.printStackTrace();
			req.getRequestDispatcher("/pages/error.jsp").forward(req, resp);
		}

	}

	public OrderModel transferInfor(UserModel user, OrderModel order) {
		order.setShipName(user.getName());
		order.setShipCity(user.getCity());
		order.setShipDistrict(user.getDistrict());
		order.setShipWard(user.getWard());
		order.setShipAddress(user.getAddress());
		order.setShipStreet(user.getStreet());
		order.setShipFloor(user.getFloor());
		order.setShipPhoneNumber(user.getPhone());
		return order;
	}
}
